package com.ansion.basedb.dao.helper;

import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.ansion.basedb.dao.GroupDao;
import com.ansion.basedb.dao.impl.GroupCachedLogicDaolmpl;
import com.ansion.basedb.dao.model.GroupModel;
import com.ansion.basedb.dao.model.UserModel;
import com.ansion.basedb.storage.StorageSdk;
import com.ansion.basedb.util.UserBroadcastUtils;
import com.ansion.bean.GroupInfo;
import com.ansion.constant.BConstant;
import com.ansion.log.VLog;
import com.ansion.utils.SettingHelper;
import com.ansion.utils.ThreadUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * Created by Andre on 23-12-26.
 */
public class GroupHelper {

    public static final String TAG = GroupHelper.class.getSimpleName();

    public static List<Long> manualLeaveGroupList = new ArrayList<>(); //记录手动离群的列表


    private static GroupDao groupDBDao;

    public static GroupDao getGroupDBDao() {
        if (groupDBDao == null) {
            synchronized (GroupDao.class) {
                if (groupDBDao == null) {
                    groupDBDao = new GroupCachedLogicDaolmpl();
                }
            }
        }
        return groupDBDao;
    }

    /**
     * 数据库通过群组id获取GroupModel
     *
     * @param uid 群组id
     * @return
     */
    @Deprecated
    public static GroupModel getGroupModel(long uid) {
        return getGroupModel(String.valueOf(uid));
    }

    public static GroupModel getGroupModel(String uid) {

        GroupDao groupDao = getGroupDBDao();
        if (groupDao == null) {
            return null;
        }
        return groupDao.getGroupModel(uid);

    }

    public static boolean isGroupSessionId(long sessionId) {

        return getGroupModel(sessionId) != null;
    }


//    private static GroupModel getGroupModel(GroupInfoPB groupInfoPB) {
//
//        GroupModel groupModel = GroupHelper.getGroupModel(groupInfoPB.gid);
//
//        if (groupModel == null) {
//            groupModel = new GroupModel();
//        }
//        groupModel.setId(groupInfoPB.gid);
//        if (!TextUtils.isEmpty(groupInfoPB.name)) {
//            groupModel.setGroupName(groupInfoPB.name);
//        } else {
//            groupModel.setDisplayName("");
//        }
//        if (!TextUtils.isEmpty(groupInfoPB.avatar)) {
//            groupModel.setGroupAvatar(ImageManager.getAvatarPreUrl(groupInfoPB.avatar));
//        }
//        if (groupInfoPB.creator != null) {
//            groupModel.setCreator(groupInfoPB.creator);
//        }
//        if (!TextUtils.isEmpty(groupInfoPB.description)) {
//            groupModel.setDiscription(groupInfoPB.description);
//        } else {
//            groupModel.setDiscription("");
//        }
//
//        if (null != groupInfoPB.update) {
//            groupModel.setGroupUpdateTime(groupInfoPB.update);
//        }
//
//        if (groupInfoPB.manager != null) {
//            groupModel.setGroupAdmin(groupModel.getAdminToString(groupInfoPB.manager));
//        }
//
//        if (groupInfoPB.type != null) {
//            groupModel.setGroupType(groupInfoPB.type);
//        }
//
//        return groupModel;
//    }
//
//    public static Set<Long> getGroupUserIds(List<GroupUserPB> userList) {
//
//        if (userList == null || userList.size() == 0) {
//            return null;
//        }
//        Set<Long> idList = new LinkedHashSet<Long>();
//        for (GroupUserPB groupUserPB : userList) {
//            idList.add(groupUserPB.uid);
//        }
//        return idList;
//    }

    /**
     * 保存群组
     *
     * @param groupModel
     */
    public static void saveGroup(GroupModel groupModel) {
        GroupDao groupDao = getGroupDBDao();
        if (groupDao == null) {
            return;
        }
        groupDao.saveGroup(groupModel);
    }

    public static void deleteGroup(long gid) {
        GroupDao groupDao = getGroupDBDao();
        if (groupDao == null) {
            return;
        }
        groupDao.deleteGroup(String.valueOf(gid));
    }

    /**
     * 用于来消息后，存储数据
     *
     */
//    public static GroupModel saveGroupFullInfoPB(GroupFullInfoPB groupFullInfoPB) {
//
//        if (groupFullInfoPB == null) {
//            return null;
//        }
//
//        GroupInfoPB groupInfoPB = groupFullInfoPB.group;
//        if (groupInfoPB == null) {
//            return null;
//        }
//
//
//        if (groupInfoPB.gid > 0) {
//            if (VLog.OPEN_LOG) {
//                VLog.e("TAG_CONTACT", "saveGroupFullInfoPB gid:%d,user:%s", groupInfoPB.gid, GroupHelper
//                        .getGroupUserIds(groupFullInfoPB
//                                .user));
//            }
//            GroupModel tmpGroup = GroupHelper.getGroupModel(groupInfoPB.gid);
//            String tmpGroupName = null;
//            if (tmpGroup != null) {
//                tmpGroupName = tmpGroup.getGroupName();
//            }
//            String oldGroupMember = (tmpGroup == null) ? null : tmpGroup.getGroupMembers();
//            GroupModel groupModel = GroupHelper
//                    .getGroupModel(groupInfoPB);
//            //更新上次请求时间，放在这里更直观一些
//            groupModel.setLastRequestTime(ServerTime.getServerTimeMillisecond());
//            if (groupFullInfoPB.user != null) {
//                Set<Long> idList = GroupHelper
//                        .getGroupUserIds(groupFullInfoPB
//                                .user);
//                groupModel.setGroupMembers(groupModel
//                        .getSetToString(idList));
//                UserFTSHelper.indexGroupMembers(Collections.singletonList(groupModel), null);
//                UserHelper.saveUserFromGroupUserPB(groupFullInfoPB.user
//                );
//            }
//
//            groupModel.setUcidLoad(true);
//            boolean avatarChanged = !StringUtils.stringIsEqual(tmpGroup == null ? null
//                    : tmpGroup.getGroupAvatar(), groupModel.getGroupAvatar());
//
//            //之前代码tmpGroup 和 groupModel 走到这一步的时候，内存对象指向同一个地址，所以nameChanged一直为false
//            boolean nameChanged = !StringUtils.stringIsEqual(tmpGroupName, groupModel.getGroupName());
//            //群成员是否发生变更
//            boolean groupMemberChange = !StringUtils.stringIsEqual(oldGroupMember, groupModel.getGroupMembers());
//            GroupHelper.saveGroup(groupModel);
//            //计算变更
//            if (avatarChanged)
//                UserChangeNotifier.getInstance().notifyAvatarChange(String.valueOf(groupModel.getId()), groupModel.getGroupAvatar());
//            if (nameChanged)
//                UserChangeNotifier.getInstance().notifyNameChange(String.valueOf(groupModel.getId()));
//            //处理群成员变更
//            if (groupMemberChange)
//                UserChangeNotifier.getInstance().notifyGroupMemberChange(String.valueOf(groupModel.getId()));
//            AZusLog.d(TAG, groupModel.toString());
//            return groupModel;
//        }
//        return null;
//
//    }

    public static void addManualLeaveGroupId(long gid) {
        if (manualLeaveGroupList != null) {
            manualLeaveGroupList.add(gid);
        }
    }

    public static boolean checkGid(long gid) {
        if (manualLeaveGroupList != null && manualLeaveGroupList.contains(gid)) {
            return true;
        }
        return false;
    }

    public static void removeManualLeaveGid(long gid) {
        if (manualLeaveGroupList != null && manualLeaveGroupList.contains(gid)) {
            manualLeaveGroupList.remove(gid);
        }
    }


    public static List<GroupModel> getAllGroupModels() {
        GroupDao groupDao = getGroupDBDao();
        if (groupDao == null) {
            return null;
        }
        return groupDao.loadAllGroups();
    }


    public static void saveFavouriteGroups(List<GroupInfo> favGroupList) {
        if (favGroupList == null) {
            return;
        }
        SettingHelper.saveFavouriteGroups(favGroupList);
        for (GroupInfo groupInfo : favGroupList) {
            GroupModel groupModel = GroupHelper.getGroupModel(groupInfo.getGid());
            if (groupModel == null) {
//                getGroupInfoRequest(groupInfo.getGid());
            }
        }
    }


    public static void saveGroupToFav(long gid) {

        GroupInfo groupInfo = new GroupInfo();
        groupInfo.setGid(gid);
        GroupModel groupModel = GroupHelper.getGroupModel(gid);
        if (groupModel != null) {
            groupInfo.setName(groupModel.getGroupName());
        }
        List<GroupInfo> favGroupList = SettingHelper.getFavouriteGroups();
        if (favGroupList == null) {
            favGroupList = new ArrayList<GroupInfo>();
        }
        if (favGroupList.size() > 0) {
            boolean needSave = true;
            for (GroupInfo data : favGroupList) {
                if (data == null) {
                    continue;
                }
                if (data.getGid() == gid) {
                    needSave = false;
                    break;
                }
            }
            if (needSave) {
                favGroupList.add(groupInfo);
            }
        } else {
            favGroupList.add(groupInfo);
        }
        saveFavouriteGroups(favGroupList);
    }

    public static void deleteGroupFromFav(long gid) {
        List<GroupInfo> favGroupList = SettingHelper.getFavouriteGroups();
        if (favGroupList == null) {
            return;
        }
        int pos = -1;
        for (int i = 0; i < favGroupList.size(); i++) {
            GroupInfo groupInfo = favGroupList.get(i);
            if (groupInfo.getGid() == gid) {
                pos = i;
                break;
            }
        }
        if (pos == -1) {
            return;
        }
        favGroupList.remove(pos);
        saveFavouriteGroups(favGroupList);
        UserBroadcastUtils.sendDeleteFavGroupIntent();
    }

    public static boolean hasFavGroup(long gid) {
        List<GroupInfo> favGroupList = SettingHelper.getFavouriteGroups();
        if (favGroupList == null) {
            return false;
        }

        int pos = -1;
        for (int i = 0; i < favGroupList.size(); i++) {
            GroupInfo groupInfo = favGroupList.get(i);
            if (groupInfo.getGid() == gid) {
                pos = i;
                break;
            }
        }
        return pos != -1;
    }


//    public static void getGroupInfoRequestIfNeed(long gid) {
//        ThreadUtil.runOnWorker(() -> {
//            if (GroupCacheServiceMgr.getSet().contains(gid)) {
//                return;
//            }
//            GroupModel model = getGroupModel(gid);
//            if (model != null &&
//                    ServerTime.getServerTimeMillisecond() - model.getLastRequestTime() > 86400 * 1000) {
//                GroupCacheServiceMgr.getSet().add(gid);
//                getGroupInfoRequest(gid);
//            }
//        });
//
//    }

    /**
     * 获取除自己以外其他成员
     *
     * @return
     */
    public static LinkedList<UserModel> getOtherUserModels(@NonNull GroupModel groupModel) {
        Set<Long> users = groupModel.getOtherUserSet();
        LinkedList<UserModel> modelList = new LinkedList<UserModel>();
        for (long userId : users) {
            UserModel userModel = UserHelper.getUserModel(userId);
            modelList.add(userModel);
        }
        return modelList;
    }

    /**
     * 注意json字段不完整！！！
     * 根据groupId 获取群成员Json
     *
     * @param groupId
     */
    public static String getGroupMembersJson(String groupId) {
        try {
            GroupModel groupModel = getGroupModel(groupId);
            if (groupModel == null) {
                return null;
            }
            Set<Long> userIdSet = groupModel.getUserIdSet();
            JSONObject jsonObject = new JSONObject();
            JSONArray itemArray = new JSONArray();
            jsonObject.put(BConstant.Contact.KEY_GROUP_MEMBER, itemArray);
            for (long userId : userIdSet) {
                UserModel userModel = UserHelper.getUserModel(userId);
                if (userModel == null) {
                    continue;
                }
                JSONObject appUserJsonByUserModel = UserHelper.getAppUserJsonByUserModel(userModel);
                if (appUserJsonByUserModel == null) {
                    continue;
                }
                itemArray.put(appUserJsonByUserModel);
            }
            return jsonObject.toString();
        } catch (Throwable e) {
            VLog.e("TAG_CONTACT", "getUserModelJson = %s", e.toString());
        }
        return null;
    }

    public static void savePrivacySettingConfig(String groupId, boolean hasShow) {
        if (!TextUtils.isEmpty(groupId)) {
            StorageSdk.getUserConfigStorage().putBoolean(String.format("%s_%s", BConstant.GroupConstant.KEY_HAS_SHOW_PRIVACY_SETTING_ADDED_BY_SOMEONE_DIALOG, groupId), hasShow);
        }
    }

    public static void savePrivacySettingConfig(String groupId, String senderUid, boolean hasShow) {
        if (!TextUtils.isEmpty(groupId)) {
            StorageSdk.getUserConfigStorage().putBoolean(String.format("%s_%s", BConstant.GroupConstant.KEY_HAS_SHOW_PRIVACY_SETTING_ADDED_BY_SOMEONE_DIALOG, groupId), hasShow);
            StorageSdk.getUserConfigStorage().putString(String.format("%s_%s", BConstant.GroupConstant.KEY_PRIVACY_SETTING_ADDED_BY_SOMEONE_SENDER, groupId), senderUid);
        }
    }

    public static void removePrivacySettingConfig(String groupId) {
        if (!TextUtils.isEmpty(groupId)) {
            StorageSdk.getUserConfigStorage().putBoolean(String.format("%s_%s", BConstant.GroupConstant.KEY_HAS_SHOW_PRIVACY_SETTING_ADDED_BY_SOMEONE_DIALOG, groupId), false);
            StorageSdk.getUserConfigStorage().putString(String.format("%s_%s", BConstant.GroupConstant.KEY_PRIVACY_SETTING_ADDED_BY_SOMEONE_SENDER, groupId), "");
        }
    }

    public static boolean hasShowPrivacySetting(String groupId) {
        return StorageSdk.getUserConfigStorage().getBoolean(String.format("%s_%s", BConstant.GroupConstant.KEY_HAS_SHOW_PRIVACY_SETTING_ADDED_BY_SOMEONE_DIALOG, groupId), false);
    }

    public static boolean isGroupSenderContact(String groupId) {
        String senderUid = StorageSdk.getUserConfigStorage().getString(String.format("%s_%s", BConstant.GroupConstant.KEY_PRIVACY_SETTING_ADDED_BY_SOMEONE_SENDER, groupId), "");
        if (!TextUtils.isEmpty(senderUid)) {
            try {
                return ContactsHelper.getContact(Long.parseLong(senderUid)) != null;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return true;
    }

}
